local lusb = require "lusb";
local format = string.format;
local desc_key = {
--[[uint8_t ]] 1,0, 'bLength',
--[[uint8_t ]] 1,1, 'bDescriptorType',
--[[uint16_t]] 2,2, 'bcdUSB',
--[[uint8_t ]] 1,4, 'bDeviceClass',
--[[uint8_t ]] 1,5, 'bDeviceSubClass',
--[[uint8_t ]] 1,6, 'bDeviceProtocol',
--[[uint8_t ]] 1,7, 'bMaxPacketSize0',
--[[uint16_t]] 2,8, 'idVendor',
--[[uint16_t]] 2,10,'idProduct',
--[[uint16_t]] 2,12,'bcdDevice',
--[[uint8_t ]] 1,14,'iManufacturer',
--[[uint8_t ]] 1,15,'iProduct',
--[[uint8_t ]] 1,16,'iSerialNumber',
--[[uint8_t ]] 1,17,'bNumConfigurations',}

for k=1,#desc_key,3 do
    local sz  = desc_key[k];
    local key = desc_key[k+2];
    local off = desc_key[k+1];
    desc_key[key] = {off,sz}
end


print();
local usb_list = {lusb.lusb_list()};
print(#usb_list);
for k=1,#usb_list,2 do
    print(string.format("%04x,%04x",usb_list[k],usb_list[k+1]));
end
--os.exit();

--daplink
local vid = 0x0d28;
local pid = 0x4011;

--wch link
local vid = 0x1a86;
local pid = 0x8011;

local usb_dev,err = lusb.lusb_open(vid,pid);
local err_str = lusb.lusb_error_name(err or 0);
--print(usb_dev,err_str);

local function usb_err(err,err2)
    if (err==0) or (not err) then return; end;
    local err_str = lusb.lusb_error_name(err);
    print(err_str);
    return true;
end

if (not usb_dev) or usb_err(err) then
    io.stderr:write('error usb!\n');
    os.exit(-1);
end

print(usb_dev);
--设置usb接口
local config,err = lusb.lusb_get_configuration(usb_dev);
print(config,err);
usb_err( lusb.lusb_set_configuration(usb_dev,config));

local desc,err = lusb.lusb_get_device_desc(usb_dev);
usb_err(err);
print(desc,err);

local desc = {ptr=desc};

desc = setmetatable(desc, {
    __index = function(self,key)
        --访问目标字段
        local att = desc_key[key] or {0,0};
        local offset = att[1];
        local sz = att[2];
        return lusb.mem_value(self.ptr,offset,sz);
    end,
})

print(desc.bLength);
print(format('%04x',desc.idVendor ));
print(format('%04x',desc.idProduct));
print(desc.bNumConfigurations);

if false then
    local ret = {lusb.lusb_get_config_descriptor(usb_dev,0)};
    print(#ret,ret[1]);
    print('===================');
    for k,v in ipairs(ret)do
        if(v=='|')then
            print('---------------');
        else
            print(v);
        end
    end
end
--usb_err( lusb.lusb_driver_active(usb_dev,2) );
usb_err( lusb.lusb_claim_interface(usb_dev,2));


local p = lusb.mem_new(1024);
local send,err =
--lusb.lusb_bulk_transfer
lusb.lusb_interrupt_transfer(usb_dev,
    0x01,
    "0123456789abcdef",0x40,
    1000
);

print(send,err);

